<template>
  <div class="user-delete-container">
    <el-card class="delete-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Delete /></el-icon>
            用户删除管理
          </span>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="searchForm.email"
              placeholder="请输入邮箱"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="searchForm.role"
              placeholder="请选择角色"
              clearable
              @change="handleSearch"
            >
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 批量操作 -->
      <div class="batch-actions">
        <el-button
          type="danger"
          :disabled="!selectedUsers.length"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除 ({{ selectedUsers.length }})
        </el-button>
        <span class="total-count">共 {{ total }} 条记录</span>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
              {{ row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'warning'">
              {{ row.status === 'active' ? '活跃' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template #default="{ row }">
            {{ row.lastLoginTime ? formatDate(row.lastLoginTime) : '从未登录' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              :disabled="row.id === currentUserId"
              @click="handleSingleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 单个删除确认对话框 -->
    <el-dialog
      v-model="deleteDialog.visible"
      title="删除用户确认"
      width="500px"
      center
    >
      <div class="delete-confirm-content">
        <div class="warning-icon">
          <el-icon size="60" color="#E6A23C">
            <WarningFilled />
          </el-icon>
        </div>
        <div class="confirm-text">
          <h3>确定要删除以下用户吗？</h3>
          <div class="user-info" v-if="deleteDialog.user">
            <p><strong>用户名：</strong>{{ deleteDialog.user.username }}</p>
            <p><strong>邮箱：</strong>{{ deleteDialog.user.email }}</p>
            <p><strong>角色：</strong>{{ deleteDialog.user.role === 'admin' ? '管理员' : '普通用户' }}</p>
          </div>
          <p class="warning-text">
            <el-icon><WarningFilled /></el-icon>
            此操作不可逆，请谨慎操作！
          </p>
        </div>
      </div>
      <template #footer>
        <el-button @click="deleteDialog.visible = false">取消</el-button>
        <el-button
          type="danger"
          :loading="deleteDialog.loading"
          @click="confirmSingleDelete"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量删除确认对话框 -->
    <el-dialog
      v-model="batchDeleteDialog.visible"
      title="批量删除用户确认"
      width="600px"
      center
    >
      <div class="delete-confirm-content">
        <div class="warning-icon">
          <el-icon size="60" color="#F56C6C">
            <WarningFilled />
          </el-icon>
        </div>
        <div class="confirm-text">
          <h3>确定要删除以下 {{ selectedUsers.length }} 个用户吗？</h3>
          <div class="batch-user-list">
            <el-scrollbar max-height="200px">
              <div
                v-for="user in selectedUsers"
                :key="user.id"
                class="batch-user-item"
              >
                <span class="username">{{ user.username }}</span>
                <span class="email">{{ user.email }}</span>
                <el-tag
                  size="small"
                  :type="user.role === 'admin' ? 'danger' : 'primary'"
                >
                  {{ user.role === 'admin' ? '管理员' : '普通用户' }}
                </el-tag>
              </div>
            </el-scrollbar>
          </div>
          <p class="warning-text">
            <el-icon><WarningFilled /></el-icon>
            此操作不可逆，将永久删除这些用户的所有数据！
          </p>
        </div>
      </div>
      <template #footer>
        <el-button @click="batchDeleteDialog.visible = false">取消</el-button>
        <el-button
          type="danger"
          :loading="batchDeleteDialog.loading"
          @click="confirmBatchDelete"
        >
          确认删除全部
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Delete,
  Search,
  Refresh,
  Message,
  WarningFilled
} from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { useAuthStore } from '@/store/auth'

// 权限检查
const authStore = useAuthStore()
if (authStore.userInfo?.role !== 'admin') {
  ElMessage.error('您没有权限访问此页面')
  // 可以重定向到其他页面
}

// 响应式数据
const loading = ref(false)
const userList = ref([])
const selectedUsers = ref([])
const total = ref(0)
const currentUserId = computed(() => authStore.userInfo?.id)

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  role: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 20
})

// 删除对话框
const deleteDialog = reactive({
  visible: false,
  loading: false,
  user: null
})

// 批量删除对话框
const batchDeleteDialog = reactive({
  visible: false,
  loading: false
})

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })

    const response = await userApi.getUserList(params)
    
    if (response.success) {
      userList.value = response.data.records || response.data.list || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getUserList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  getUserList()
}

// 选择变化
const handleSelectionChange = (selection) => {
  // 过滤掉当前登录用户
  selectedUsers.value = selection.filter(user => user.id !== currentUserId.value)
}

// 单个删除
const handleSingleDelete = (user) => {
  if (user.id === currentUserId.value) {
    ElMessage.warning('不能删除当前登录用户')
    return
  }
  
  deleteDialog.user = user
  deleteDialog.visible = true
}

// 确认单个删除
const confirmSingleDelete = async () => {
  try {
    deleteDialog.loading = true
    const response = await userApi.deleteUser(deleteDialog.user.id)
    
    if (response.success) {
      ElMessage.success('删除成功')
      deleteDialog.visible = false
      getUserList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除失败')
  } finally {
    deleteDialog.loading = false
  }
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedUsers.value.length) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  batchDeleteDialog.visible = true
}

// 确认批量删除
const confirmBatchDelete = async () => {
  try {
    batchDeleteDialog.loading = true
    const userIds = selectedUsers.value.map(user => user.id)
    const response = await userApi.batchDeleteUsers(userIds)
    
    if (response.success) {
      ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`)
      batchDeleteDialog.visible = false
      selectedUsers.value = []
      getUserList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  } finally {
    batchDeleteDialog.loading = false
  }
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  getUserList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  getUserList()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-delete-container {
  padding: 20px;
}

.delete-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #E6A23C;
}

.search-section {
  margin-bottom: 20px;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.total-count {
  color: #666;
  font-size: 14px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 确认对话框样式 */
.delete-confirm-content {
  text-align: center;
  padding: 20px;
}

.warning-icon {
  margin-bottom: 20px;
}

.confirm-text h3 {
  margin: 0 0 20px 0;
  color: #303133;
}

.user-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin: 15px 0;
  text-align: left;
}

.user-info p {
  margin: 8px 0;
  color: #606266;
}

.warning-text {
  color: #E6A23C;
  font-weight: bold;
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

/* 批量删除用户列表 */
.batch-user-list {
  margin: 15px 0;
  text-align: left;
}

.batch-user-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  background: #f5f7fa;
}

.batch-user-item .username {
  font-weight: bold;
  color: #303133;
  min-width: 80px;
}

.batch-user-item .email {
  color: #606266;
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-delete-container {
    padding: 10px;
  }
  
  .search-section .el-col {
    margin-bottom: 10px;
  }
  
  .batch-actions {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>